<template>
	<view class="container">
		<view class="header-image-box">
			<u-image shape="circle"
				:src="headImage"
				mode="" width="200" height="200"></u-image>
		</view>
		<view class="text-box" style="font-size: 35rpx;">
			<span>来得好 没有中介费烦恼</span>
		</view>
		<view class="btn-box">
			<u-button type="success" ripple v-show="isShow" @click="getUserInfo">微信授权登录</u-button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				userInfo: '',
				avatarUrl: '',
				nickName: '',
				code: '',
				isShow: false,
				headImage: require('../../static/laiPic.jpg')
			}
		},
		async onLoad() {
			// this.login()
			this.logRequset();
		},
		methods: {
			//授权
			async login() {
				var that = this	
				if(wx.getStorageSync("scope.userInfo") === 1){
					//已经授权过，直接登录
					that.logRequset(null)
				}else{
					//授权
					this.isShow = true
				}
			},
			//微信授权
			getUserInfo(){
				var that = this
				wx.getUserProfile({
					desc: '获得你的昵称、头像、地区及性别',
					success: (res) => {
						// console.log(res)
						wx.setStorageSync("scope.userInfo",1)//标记授权状态
						wx.setStorage({
							key: "user",
							data: res.userInfo,
							success() {
								that.logRequset(res.userInfo)
							},
							fail(){
								
							}
						})
					},
					fail: (res) => {
						console.log(res)
						wx.showToast({
							title: '您拒绝了授权',
							icon: 'none',
							duration: 2000
						})
						// that.logRequset(null)
						wx.navigateBack({
							delta: 1
						})
					}
				})
			},
			
			//登录
			async logRequset(userInfo) {
				//请求登录获取code
				let userLogin = await wx.login({})
				this.code = userLogin.code
				// console.log(this.code)
				//添加登录的用户信息
				let userLog = await this.$request({
					url: '/v1/common/wx/login',
					method: 'POST',
					data: {
						"code": this.code,
						"rawData": JSON.stringify(userInfo)
					}
				})
				// console.log("userLog", userLog)
				if (userLog.isSuccess) {
					// console.log("userLog", userLog)
					//添加成功保存用户的openId
					// getApp().globalData.openId = userLog.data.openId
					getApp().globalData.userId = userLog.data.id
					// wx.navigateBack()
					wx.switchTab({
						url: '/pages/index/index'
					})
				}
			},
			gotoIndex(userInfo) {
				//将userInfo传入后端				
				// wx.switchTab({
				// 	url: '/pages/index/index'
				// })
				wx.navigateBack()
			}
		}
	}
</script>

<style scoped>
	.container {
		height: 100%;
		position: relative;
	}

	.btn-box,
	.text-box,
	.header-image-box {
		position: absolute;
		width: fit-content;
		left: 50%;
	}

	.btn-box {
		top: 50%;
		transform: translateX(-50%) translateY(-40%);
	}

	.text-box {
		top: 40%;
		transform: translateX(-50%) translateY(-40%);
	}

	.header-image-box {
		top: 25%;
		transform: translateX(-50%) translateY(-40%);
	}
</style>
